<?php

namespace addons\shopro\job;

use addons\shopro\service\Wallet as WalletService;
use app\admin\model\shopro\commission\Reward as RewardModel;
use app\admin\model\shopro\commission\Reward1;
use app\admin\model\shopro\Config;
use app\admin\model\shopro\user\User as UserModel;
use app\admin\model\shopro\user\WalletLog;
use think\queue\Job;
use think\Db;
use think\exception\HttpResponseException;
use app\admin\model\shopro\order\Order;
use addons\shopro\traits\StockSale;
use app\admin\model\shopro\user\User;
use app\admin\model\shopro\order\Invoice as OrderInvoice;
use addons\shopro\service\order\OrderOper;
use addons\shopro\facade\Activity as ActivityFacade;

/**
 * 订单自动操作
 */
class OrderPaid extends BaseJob
{

    use StockSale;

    /**
     * 订单支付完成
     */
    public function paid(Job $job, $data)
    {
        try {
            $order = $data['order'];
            $user = $data['user'];
            $order = Order::with('items')->where('id', $order['id'])->find();
            $user = User::get($user['id']);
echo date("Ymd H:i:s")."_shopro-high_order_".$order->id;
            // 数据库删订单的问题常见，这里被删的订单直接把队列移除
            if ($order) {
                //更新当前用户最后一次的消费总额
                $order_amount = $order->order_amount;
                Db::name("shopro_commission_agent")->where(['user_id' => $user->id])->update(['once_order_money_all' => $order_amount]);
                //$this->forwardStockSale($order);
                //发放分红
                //$this->fenhong($order);
                Db::transaction(function () use ($order, $user, $data) {
                    // 订单减库存
                    $this->forwardStockSale($order);
                    //发放分红
                  //  $this->fenhong($order);

                    //发放3500加权分红
               //     $this->jiaquanfenhong($order);
                    //发放锁仓积分释放
                   // $this->user_integral_release($order);
                    // 处理发票审核改为等待开具
                    if ($order->invoice_status == 1) {
                        $invoice = OrderInvoice::where('order_id', $order->id)->find();
                        if ($invoice) {
                            $invoice->status = 'waiting';
                            $invoice->save();
                        }
                    }

                    // 处理活动，加入拼团，完成拼团，添加赠品记录等
                    ActivityFacade::buyOk($order, $user);

                    // 将订单参与活动信息改为已支付
                    $orderOper = new OrderOper();
                    $orderOper->activityOrderPaid($order);

                    // 触发订单支付完成事件
                    $data = ['order' => $order, 'user' => $user];
                    \think\Hook::listen('order_paid_after', $data);
                });
            }

            // 删除 job
            $job->delete();
        } catch (HttpResponseException $e) {
            Db::rollback();
            $data = $e->getResponse()->getData();
            $message = $data ? ($data['msg'] ?? '') : $e->getMessage();
            format_log_error($e, 'OrderPaid.paid.HttpResponseException', $message);
        } catch (\Exception $e) {
            Db::rollback();
            // 队列执行失败
            format_log_error($e, 'OrderPaid.paid');
        }
    }

    /**
     * @Description: 1星 3%, 2星 2%, 3星 1%
     * @param $order
     */
    public function fenhong($order,$bonus1,$bonus2,$bonus3,$bonus4,$bonus5,$bonus6,$bonus7)
    {
        $tocommission = 0.8;//佣金
        $tomoney = 1 - $tocommission;//余额


        $userId = $order->user_id;
        $order_amount = $order->order_amount;
        \think\Log::info('开始执行分红_'.$userId."_订单总金额_".$order_amount);
        \think\Log::info('获取所有1星2星3星');
        $list = Db::name("shopro_commission_agent")->whereIn('level', [2,3,4,5,6,7])->select();
        if(empty($list))
        {
            \think\Log::info('没有分红分销商');
        }
        $level1 = $level2 = $level3 = $level4 = $level5 = $level6 = $level7 = [];
        foreach ($list as $item)
        {
        /*    if($item['level'] >= 1)
            {
                $level1[] = $item['user_id'];
            }*/
            if($item['level'] >= 2)
            {
                $level2[] = $item['user_id'];
            }
            if($item['level'] >= 3)
            {
                $level3[] = $item['user_id'];
            }
            if($item['level'] >= 4)
            {
                $level4[] = $item['user_id'];
            }
            if($item['level'] >= 5)
            {
                $level5[] = $item['user_id'];
            }
            if($item['level'] >= 6)
            {
                $level6[] = $item['user_id'];
            }
            if($item['level'] == 7)
            {
                $level7[] = $item['user_id'];
            }
        }
     //   $count1 = count($level1);
        $count2 = count($level2);
        $count3 = count($level3);
        $count4 = count($level4);
        $count5 = count($level5);
        $count6 = count($level6);
        $count7 = count($level7);
    //    $ratio1=$bonus1/100;
        $ratio2=$bonus2/100;
        $ratio3=$bonus3/100;
        $ratio4=$bonus4/100;
        $ratio5=$bonus5/100;
        $ratio6=$bonus6/100;
        $ratio7=$bonus7/100;
        $fen2 = $count2 > 0 ? sprintf("%0.5f", ($order_amount*$ratio2/$count2)*$tocommission) : 0;
        $fen2_m = $count2 > 0 ? sprintf("%0.5f", ($order_amount*$ratio2/$count2)*$tomoney) : 0;
        $fen3 = $count3 > 0 ? sprintf("%0.5f", ($order_amount*$ratio3/$count3)*$tocommission) : 0;
        $fen3_m = $count3 > 0 ? sprintf("%0.5f", ($order_amount*$ratio3/$count3)*$tomoney) : 0;
        $fen4 = $count4 > 0 ? sprintf("%0.5f", ($order_amount*$ratio4/$count4)*$tocommission) : 0;
        $fen4_m = $count4 > 0 ? sprintf("%0.5f", ($order_amount*$ratio4/$count4)*$tomoney) : 0;
        $fen5 = $count5 > 0 ? sprintf("%0.5f", ($order_amount*$ratio5/$count5)*$tocommission) : 0;
        $fen5_m = $count5 > 0 ? sprintf("%0.5f", ($order_amount*$ratio5/$count5)*$tomoney) : 0;
        $fen6 = $count6 > 0 ? sprintf("%0.5f", ($order_amount*$ratio6/$count6)*$tocommission) : 0;
        $fen6_m = $count6 > 0 ? sprintf("%0.5f", ($order_amount*$ratio6/$count6)*$tomoney) : 0;
        $fen7 = $count7 > 0 ? sprintf("%0.5f", ($order_amount*$ratio7/$count7)*$tocommission) : 0;
        $fen7_m = $count7 > 0 ? sprintf("%0.5f", ($order_amount*$ratio7/$count7)*$tomoney) : 0;

        \think\Log::info('1星总数'.$count2."_单个分红_".$fen2);
        \think\Log::info('2星总数'.$count3."_单个分红_".$fen3);
        \think\Log::info('3星总数'.$count4."_单个分红_".$fen4);
        \think\Log::info('4星总数'.$count5."_单个分红_".$fen5);
        \think\Log::info('5星总数'.$count6."_单个分红_".$fen6);
        \think\Log::info('6星总数'.$count7."_单个分红_".$fen7);
        if(!empty($level2))
        {
            foreach ($level2 as $uid2)
            {
                $commissionRewardParams = [
                    'order_id' => $order['id'],
                    'order_item_id' => $order['id'],
                    'buyer_id' => $userId,      // 购买人
                    'commission_order_id' => $order['id'],   // 分销订单ID
                    'agent_id' => $uid2,           // 待分佣分销商ID
                    'type' => 'commission',                               // 奖金类型
                    'commission' => $fen2,                     // 佣金
                    //'status' => 0,                              // 佣金状态
                    'status' => 1,                              // 佣金状态
                    'original_commission' => 0,            // 原始佣金
                    'commission_level' => 0,   // 分佣层级
                    'commission_rules' => '',   // 分佣层级
                    'agent_level' => 0,              // 分佣时分销商等级
                    'commission_time' => time()
                ];
                //创建佣金明细
                \think\Log::info("分给{$uid2}_".$fen2);
                $commissionReward = RewardModel::create($commissionRewardParams);
                if($fen2>0){
                    $user = UserModel::getById($uid2);
                    if(!empty($user)){
                        WalletService::change($uid2, 'commission', $fen2, 'fenhong', [
                            'order_id' => $order['id'],
                        ]);
                    }

                }

                if($fen2_m>0) {
                    $user = UserModel::getById($uid2);
                    if(!empty($user)) {
                        WalletService::change($uid2, 'money', $fen2_m, 'fenhong1', [
                            'order_id' => $order['id'],
                        ]);
                    }
                }
            }
        }

        if(!empty($level3))
        {
            foreach ($level3 as $uid3)
            {
                $commissionRewardParams = [
                    'order_id' => $order['id'],
                    'order_item_id' => $order['id'],
                    'buyer_id' => $userId,      // 购买人
                    'commission_order_id' => $order['id'],   // 分销订单ID
                    'agent_id' => $uid3,           // 待分佣分销商ID
                    'type' => 'commission',                               // 奖金类型
                    'commission' => $fen3,                     // 佣金
                    //'status' => 0,                              // 佣金状态
                    'status' => 1,                              // 佣金状态
                    'original_commission' => 0,            // 原始佣金
                    'commission_level' => 0,   // 分佣层级
                    'commission_rules' => '',   // 分佣层级
                    'agent_level' => 0 ,             // 分佣时分销商等级
                    'commission_time' => time()
                ];
                \think\Log::info("分给{$uid3}_".$fen3);
                //创建佣金明细
                $commissionReward = RewardModel::create($commissionRewardParams);
                $user = UserModel::getById($uid3);
                if(!empty($user)&&$fen3>0) {
                    WalletService::change($uid3, 'commission', $fen3, 'fenhong', [
                        'order_id' => $order['id'],
                    ]);
                }
                if(!empty($user)&&$fen3_m>0) {
                    WalletService::change($uid3, 'money', $fen3_m, 'fenhong1', [
                        'order_id' => $order['id'],
                    ]);
                }
            }
        }
        if(!empty($level4))
        {
            foreach ($level4 as $uid4)
            {
                $commissionRewardParams = [
                    'order_id' => $order['id'],
                    'order_item_id' => $order['id'],
                    'buyer_id' => $userId,      // 购买人
                    'commission_order_id' => $order['id'],   // 分销订单ID
                    'agent_id' => $uid4,           // 待分佣分销商ID
                    'type' => 'commission',                               // 奖金类型
                    'commission' => $fen4,                     // 佣金
                    //'status' => 0,                              // 佣金状态
                    'status' => 1,                              // 佣金状态
                    'original_commission' => 0,            // 原始佣金
                    'commission_level' => 0,   // 分佣层级
                    'commission_rules' => '',   // 分佣层级
                    'agent_level' => 0 ,             // 分佣时分销商等级
                    'commission_time' => time()
                ];
                //创建佣金明细
                \think\Log::info("分给{$uid4}_".$fen4);
                $commissionReward = RewardModel::create($commissionRewardParams);
                $user = UserModel::getById($uid4);
                if(!empty($user)) {
                    if($fen4>0){
                        WalletService::change($uid4, 'commission', $fen4, 'fenhong', [
                            'order_id' => $order['id'],
                        ]);
                    }


                    if($fen4_m>0){
                        WalletService::change($uid4, 'money', $fen4_m, 'fenhong1', [
                            'order_id' => $order['id'],
                        ]);
                    }

                }
            }
        }
        if(!empty($level5))
        {
            foreach ($level5 as $uid5)
            {
                $commissionRewardParams = [
                    'order_id' => $order['id'],
                    'order_item_id' => $order['id'],
                    'buyer_id' => $userId,      // 购买人
                    'commission_order_id' => $order['id'],   // 分销订单ID
                    'agent_id' => $uid5,           // 待分佣分销商ID
                    'type' => 'commission',                               // 奖金类型
                    'commission' => $fen5,                     // 佣金
                    //'status' => 0,                              // 佣金状态
                    'status' => 1,                              // 佣金状态
                    'original_commission' => 0,            // 原始佣金
                    'commission_level' => 0,   // 分佣层级
                    'commission_rules' => '',   // 分佣层级
                    'agent_level' => 0 ,             // 分佣时分销商等级
                    'commission_time' => time()
                ];
                //创建佣金明细
                \think\Log::info("分给{$uid5}_".$fen5);
                $commissionReward = RewardModel::create($commissionRewardParams);
                $user = UserModel::getById($uid5);
                if(!empty($user)) {
                    if($fen5>0){
                        WalletService::change($uid5, 'commission', $fen5, 'fenhong', [
                            'order_id' => $order['id'],
                        ]);

                    }
                    if($fen5_m>0){
                        WalletService::change($uid5, 'money', $fen5_m, 'fenhong1', [
                            'order_id' => $order['id'],
                        ]);
                    }

                }
            }
        }
        if(!empty($level6))
        {
            foreach ($level6 as $uid6)
            {
                $commissionRewardParams = [
                    'order_id' => $order['id'],
                    'order_item_id' => $order['id'],
                    'buyer_id' => $userId,      // 购买人
                    'commission_order_id' => $order['id'],   // 分销订单ID
                    'agent_id' => $uid6,           // 待分佣分销商ID
                    'type' => 'commission',                               // 奖金类型
                    'commission' => $fen6,                     // 佣金
                    //'status' => 0,                              // 佣金状态
                    'status' => 1,                              // 佣金状态
                    'original_commission' => 0,            // 原始佣金
                    'commission_level' => 0,   // 分佣层级
                    'commission_rules' => '',   // 分佣层级
                    'agent_level' => 0 ,             // 分佣时分销商等级
                    'commission_time' => time()
                ];
                //创建佣金明细
                \think\Log::info("分给{$uid6}_".$fen6);
                $commissionReward = RewardModel::create($commissionRewardParams);
                $user = UserModel::getById($uid6);
                if(!empty($user)) {
                    if ($fen6 > 0) {
                        WalletService::change($uid6, 'commission', $fen6, 'fenhong', [
                            'order_id' => $order['id'],
                        ]);
                    }

                    if ($fen6_m > 0) {
                        WalletService::change($uid6, 'money', $fen6_m, 'fenhong1', [
                            'order_id' => $order['id'],
                        ]);
                    }
                }

            }
        }
        if(!empty($level7))
        {
            foreach ($level7 as $uid7)
            {
                $commissionRewardParams = [
                    'order_id' => $order['id'],
                    'order_item_id' => $order['id'],
                    'buyer_id' => $userId,      // 购买人
                    'commission_order_id' => $order['id'],   // 分销订单ID
                    'agent_id' => $uid7,           // 待分佣分销商ID
                    'type' => 'commission',                               // 奖金类型
                    'commission' => $fen7,                     // 佣金
                    //'status' => 0,                              // 佣金状态
                    'status' => 1,                              // 佣金状态
                    'original_commission' => 0,            // 原始佣金
                    'commission_level' => 0,   // 分佣层级
                    'commission_rules' => '',   // 分佣层级
                    'agent_level' => 0 ,             // 分佣时分销商等级
                    'commission_time' => time()
                ];
                //创建佣金明细
                \think\Log::info("分给{$uid7}_".$fen7);
                $commissionReward = RewardModel::create($commissionRewardParams);
                $user = UserModel::getById($uid7);
                if(!empty($user)) {
                    if ($fen7 > 0) {
                        WalletService::change($uid7, 'commission', $fen7, 'fenhong', [
                            'order_id' => $order['id'],
                        ]);
                    }

                    if ($fen7_m > 0) {
                        WalletService::change($uid7, 'money', $fen7_m, 'fenhong1', [
                            'order_id' => $order['id'],
                        ]);
                    }
                }

            }
        }

    }
    /**
     * @Description: 全平台加权分红
     * @param $order
     */
    public function jiaquanfenhong($order,$bonus_rate)
    {
        $tocommission = 0.8;//佣金
        $tomoney = 1 - $tocommission;//余额


        $userId = $order->user_id;
        $order_amount = $order->order_amount;
        \think\Log::info('开始执行加权分红_'.$userId."_订单总金额_".$order_amount);
        \think\Log::info('获取所有满足条件的会员');
        $list = Db::name("user")->where('total_consume','>=',3500)->select();
        //$list=User::where('total_consume','>=',3500)->select();;
     //   $bonus_rate = Config::getConfigs('shop.commission.bonus_rate', false);
       // $bonus_rate=10;
        if(empty($list))
        {
            \think\Log::info('没有分红会员');
        }
     /*   $level2 = [];
        foreach ($list as $item)
        {
                $level2[] = $item['user_id'];
        }*/
        $count = count($list);
        $amount=$order_amount*$bonus_rate/100;
        $total_consume = Db::name("user")->where('total_consume','>=',3500)
            ->sum('total_consume');

  /*      $fen2 = $count2 > 0 ? sprintf("%0.2f", ($amount/$count2)*$tocommission) : 0;
        $fen2_m = $count2 > 0 ? sprintf("%0.2f", ($amount/$count2)*$tomoney) : 0;*/
        \think\Log::info('会员总数'.$count."_总分红_".$amount);
        if($list&&$total_consume>0)
        {
            foreach ($list as $u)
            {
                $weighting=$u['total_consume']/$total_consume;
                $fen2 = $weighting > 0 ? sprintf("%0.5f", ($amount*$weighting)*$tocommission) : 0;
                $fen2_m = $weighting > 0 ? sprintf("%0.5f", ($amount*$weighting)*$tomoney) : 0;
                $commissionRewardParams = [
                    'order_id' => $order['id'],
                    'order_item_id' => $order['id'],
                    'buyer_id' => $userId,      // 购买人
                    'commission_order_id' => $order['id'],   // 分销订单ID
                    'agent_id' => $u['id'],           // 待分佣分销商ID
                    'type' => 'commission',                               // 奖金类型
                    'commission' => $fen2,                     // 佣金
                    //'status' => 0,                              // 佣金状态
                    'status' => 1,                              // 佣金状态
                    'original_commission' => 0,            // 原始佣金
                    'commission_level' => 0,   // 分佣层级
                    'commission_rules' => '',   // 分佣层级
                    'agent_level' => 0,              // 分佣时分销商等级
                    'commission_time' => time()
                ];
                //创建佣金明细
                \think\Log::info("分给{$u['id']}_".$fen2);
                $commissionReward = RewardModel::create($commissionRewardParams);
                if($fen2>0){
                    WalletService::change($u['id'], 'commission', $fen2, 'jiaquan', [
                        'order_id' => $order['id'],
                    ]);
                }

                if($fen2_m>0){
                    WalletService::change($u['id'], 'money', $fen2_m, 'jiaquan', [
                        'order_id' => $order['id'],
                    ]);
                }

            }
        }
    }
   /**
     * @Description: 锁仓积分释放
     * @param $order
     */
    public function user_integral_release($order)
    {
        $tocommission = 0.5;//佣金
        $tomoney = 1 - $tocommission;//余额


        $userId = $order->user_id;
        $order_amount = $order->order_amount;
        \think\Log::info('开始执行锁仓释放_'.$userId."_订单总金额_".$order_amount);
        \think\Log::info('获取所有满足条件的会员');
    /*    $user = Db::name("user")->where('id',$userId)->find();
           if(!empty($user['father_user_id'])){
           $userbonus = Db::name("user")
               ->where('id',$user['father_user_id'])
               ->find();
       }else{
           $userbonus = Db::name("user")
               ->where('id',$user['parent_user_id'])
               ->find();
       }*/
        $userbonus=$this->get_user_integral_release($userId);

        if(empty($userbonus))
        {
            \think\Log::info('没有释放会员');
        }else{
            if($userbonus['integral_release']>0){
                $bonus_rate = $userbonus['integral_release'];

                $amount=$order_amount*$bonus_rate/100;
                if($amount>$userbonus['integral']){
                    $amount=$userbonus['integral'];
                }
            }else{
                $amount=0;
            }


            \think\Log::info('会员总数1'."_总释放_".$amount);

            if($userbonus&&$amount>0&&$userbonus['integral']>0)
            {

                $weighting=$amount;
                $fen2 = $weighting > 0 ? sprintf("%0.5f", ($amount)*$tocommission) : 0;
                $fen2_m = $weighting > 0 ? sprintf("%0.5f", ($amount)*$tomoney) : 0;
                $commissionRewardParams = [
                    'order_id' => $order['id'],
                    'order_item_id' => $order['id'],
                    'buyer_id' => $userId,      // 购买人
                    'commission_order_id' => $order['id'],   // 分销订单ID
                    'agent_id' => $userbonus['id'],           // 待分佣分销商ID
                    'type' => 'commission',                               // 奖金类型
                    'commission' => $fen2,                     // 佣金
                    //'status' => 0,                              // 佣金状态
                    'status' => 1,                              // 佣金状态
                    'original_commission' => 0,            // 原始佣金
                    'commission_level' => 0,   // 分佣层级
                    'commission_rules' => '',   // 分佣层级
                    'agent_level' => 0,              // 分佣时分销商等级
                    'commission_time' => time()
                ];
                //创建佣金明细
                \think\Log::info("分给{$userbonus['id']}_".$fen2);
                $commissionReward = RewardModel::create($commissionRewardParams);
                if($fen2>0){
                    WalletService::change($userbonus['id'], 'commission', $fen2, 'shifang', [
                        'order_id' => $order['id'],
                    ]);

                }
                if($amount>0){
                    WalletService::change($userbonus['id'], 'integral', -$amount, 'shifang', [
                        'order_id' => $order['id'],
                    ]);

                 }

                $sys_fund = Config::getConfigs('shop.basic.sys_fund', false);;
                $sys_green_score = Config::getConfigs('shop.basic.sys_green_score', false);
                $perprice = $sys_fund/$sys_green_score;
                $perprice = sprintf("%.4f", $perprice);
                //系统资金增加
                if($fen2_m > 0)
                {
                    $commissionRewardParams = [
                        'order_id' => $order['id'],
                        'order_item_id' => $order['id'],
                        'buyer_id' => $userId,      // 购买人
                        'commission_order_id' => $order['id'],   // 分销订单ID
                        'agent_id' => $userId,           // 待分佣分销商ID
                        'type' => 'money',                               // 奖金类型
                        'commission' => $fen2_m,                     // 佣金
                        'status' => 1,                              // 佣金状态
                        'original_commission' => 0,            // 原始佣金
                        'commission_level' => 0,   // 分佣层级
                        'commission_rules' => '',   // 分佣层级
                        'agent_level' => 0,              // 分佣时分销商等级
                        'commission_time' => time()
                    ];
                    $commissionReward = Reward1::create($commissionRewardParams);
                    //$configs = Db::name('shopro_config')->where(['code' =>'shop.basic.sys_fund'])->find();     //('shop.basic.sys_fund', false);
                    //$value = $configs['value'] ?? 0;
                    //$configs = Db::name('')['value' =>$value+$sys_fund_give])->where(['code' =>'shop.basic.sys_fund']);     //('shop.basic.sys_fund', false);
                    Db::name('shopro_config')->query("update fa_shopro_config set value=value+{$fen2_m} where code ='shop.basic.sys_fund'");
                    $sys_fund = Config::getConfigs('shop.basic.sys_fund', false);
                    if($fen2_m>0){
                        WalletService::change($userbonus['id'], WalletLog::SYS_FUND_TYPE, $fen2_m, 'order_give2', [
                            'order_id' => $order['id'],
                        ], '', $perprice, $sys_fund);
                    }

                    //更新系统资金总数

                    //LogModel::add($commissionReward['agent_id'], 'reward', [
                    //    'type' => 'paid',
                    //    'reward' => $commissionReward,
                    //], $this->buyer->user);
                }
                if($fen2_m > 0)
                {
                 /*   //赠送金
                    WalletService::change($userbonus['id'], WalletLog::GREEN_SCORE_GIFT_TYPE, $fen2_m, 'order_give', [
                        'order_id' => $order['id'],
                    ]);*/
                    $sys_fund = Config::getConfigs('shop.basic.sys_fund', false);;
                    $sys_green_score = Config::getConfigs('shop.basic.sys_green_score', false);
                    $perprice = $sys_fund/$sys_green_score;
                    $perprice = sprintf("%.4f", $perprice);
                    $give = sprintf("%.2f", $fen2_m/$perprice);
                    //绿色积分
                    \think\Log::info("单价{$perprice},绿色积分{$give}");
                    if($give>0){
                        WalletService::change($userbonus['id'], WalletLog::GREEN_SCORE_TYPE, $give, 'order_give1', [
                            'order_id' => $order['id'],
                        ], '', $perprice);
                    }

                    Db::name('shopro_config')->query("update fa_shopro_config set value=value+{$give} where code ='shop.basic.sys_green_score'");
                }


                /*          WalletService::change($u['id'], 'money', $fen2_m, 'jiaquan', [
                              'order_id' => $order['id'],
                          ]);*/

            }
        }

    }
/**
 * 递归寻找符合释放条件的会员
 *
 */
    public function get_user_integral_release($id){
        $user = Db::name("user")->where('id',$id)->find();
        if($user['integral']>0){
      /*      if(!empty($user['father_user_id'])){
                $userbonus = Db::name("user")
                    ->where('id',$user['father_user_id'])
                    ->find();
            }else{*/
            $userbonus=$user;


           // }
        }else{
            if(empty($user['parent_user_id'])){
                return array();
            }else{
                $userbonus = Db::name("user")
                    ->where('id',$user['parent_user_id'])
                    ->find();
            }
        }

        if(empty($userbonus)){
            return false;
        }else{
            if($userbonus['integral']>0){
                return $userbonus;
            }else{
              return  $this->get_user_integral_release($userbonus['id']);
            }
        }

    }
    /**
     * 订单选择线下支付(货到付款)完成
     */
    public function offline(Job $job, $data)
    {
        try {
            $order = $data['order'];
            $user = $data['user'];

            $order = Order::with('items')->where('id', $order['id'])->find();
            $user = User::get($user['id']);

            // 数据库删订单的问题常见，这里被删的订单直接把队列移除
            if ($order) {
                Db::transaction(function () use ($order, $user, $data) {
                    // 订单减库存
                    $this->forwardStockSale($order);

                    // 处理活动，加入拼团，完成拼团，添加赠品记录等
                    ActivityFacade::buyOk($order, $user);

                    // 触发订单选择线下支付(货到付款)完成事件
                    $data = ['order' => $order, 'user' => $user];
                    \think\Hook::listen('order_offline_after', $data);
                });
            }

            // 删除 job
            $job->delete();
        } catch (HttpResponseException $e) {
            $data = $e->getResponse()->getData();
            $message = $data ? ($data['msg'] ?? '') : $e->getMessage();
            format_log_error($e, 'OrderPaid.offline.HttpResponseException', $message);
        } catch (\Exception $e) {
            // 队列执行失败
            format_log_error($e, 'OrderPaid.offline');
        }
    }
}